package com.lmm.lcbusiness.lcbusiness.config;


import com.lmm.lcbusiness.lcbusiness.dbmodel.AppKeyValueModel;
import com.lmm.lcbusiness.lcbusiness.utils.RealmUtils;

import io.realm.Realm;
import io.realm.exceptions.RealmMigrationNeededException;

/**
 * Created by xmgong on 2016/12/14.
 */

public class AppKeyValueUtils {


    public static String getValue(String key) {
        String value = "";
        Realm realm = RealmUtils.getRealm();
        AppKeyValueModel vam = realm.where(AppKeyValueModel.class).equalTo("Key", key).findFirst();
        if (vam != null) {
            value = vam.getValue();
        }
        return value;
    }

    public static void setValue(final String key, final String va) {
        Realm realm = null;
        try {
            realm = RealmUtils.getRealm();
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    AppKeyValueModel avm = realm.where(AppKeyValueModel.class).equalTo("Key", key).findFirst();
                    if (avm == null) {
                        avm = realm.createObject(AppKeyValueModel.class, key);
                        avm.setValue(va);
                    } else {
                        avm.setValue(va);
                    }

                }
            });
        } catch (RealmMigrationNeededException e) {
            e.printStackTrace();
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }


}
